package com.xing.morethread.utils;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * 自定义线程池来使用@Async
 */
@Configuration //交给spring管理，让spring能扫描到
@EnableAsync  //开启异步任务的支持
public class Threadconfig {

    @Bean(name = "pool1") //交给spring管理，起名，可以配置多个线程
    public Executor createExecutor(){
        //创建线程池任务执行对象
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(1); //设置核心线程数（默认线程数）
        threadPoolTaskExecutor.setMaxPoolSize(5); //设置最大线程数
        threadPoolTaskExecutor.setKeepAliveSeconds(60); //允许线程空闲时间（单位：默认为秒）
        threadPoolTaskExecutor.setQueueCapacity(200); //缓冲队列数
        threadPoolTaskExecutor.setThreadNamePrefix("xfhThread"); //线程池名前缀
        //线程池对拒绝任务的处理策略
        //abortPolicy： 中断拒绝，丢弃任务并抛出异常（核心业务用的多）
        //DiscardPolicy：丢弃任务并不会抛出异常（非核心业务可以用）
        //DiscardOldestpolicy:把队列中等待最久的任务丢弃，将新的任务加入到队列中
        //CallerRunsPolicy:任务由主线程执行，这种策略不会丢弃任务，也不会抛出异常，将任务会退给调用者
        ThreadPoolExecutor.AbortPolicy abortPolicy = new ThreadPoolExecutor.AbortPolicy();
        threadPoolTaskExecutor.setRejectedExecutionHandler(abortPolicy);
        return threadPoolTaskExecutor;
    }

    @Bean(name = "pool2") //交给spring管理，起名，可以配置多个线程池
    public ThreadPoolTaskExecutor createExecutor2(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(1); //核心线程数
        threadPoolTaskExecutor.setMaxPoolSize(2);  //最大线程数
        threadPoolTaskExecutor.setKeepAliveSeconds(60); //允许线程空闲时间（单位：默认为秒）
        threadPoolTaskExecutor.setQueueCapacity(200); //缓冲队列数
        //线程池名前缀
        threadPoolTaskExecutor.setThreadNamePrefix("xfhThread2");
        //线程池对拒绝任务的处理策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return threadPoolTaskExecutor;
    }
    
}
